import { HttpHandler,Entity,Entities,DBAccess, WebUser} from './Gener.js';
import {webPath,plant,} from './config.js';
import {GenerDevelopFrm} from './FrmDevelop.js';
import {GenerFoolFrm} from './FrmFool.js';
import {GenerFreeFrm} from './FrmFree.js';
import {GenerCheckNames,checkBlanks,checkReg,validate} from './tools.js';
import $ from 'jquery'

//定义全局的MyFlowGener.vue的组件
var _this;
/**
 * 初始化按钮
 */
function initToolBar(obj) {
    //按钮初始化
    _this = obj;
    console.log("--===---===----===-",_this.$route.params);
      var handler = new HttpHandler("BP.WF.HttpHandler.WF_MyFlow");
      handler.AddJson( _this.$route.params);
      var data = handler.DoMethodReturnString("InitToolBarForVue"); //执行保存方法.
      if(data.indexOf("err@")!=-1){
        _this.$alert(data.replace('err@',''), {
            dangerouslyUseHTMLString: true
        });
        return;
      }
      data = JSON.parse(data);
      _this.toolBtns = data;
}
// 枚举值
const FrmRBs=[];

/**
 * 获取表单数据
 */
function GenerWorkNode(obj){
    _this = obj;
    console.log("获取表单数据-------",_this.$route.params);
    //获取表单的内容
    var handler = new HttpHandler("BP.WF.HttpHandler.WF_MyFlow");
    handler.AddJson(_this.$route.params);
   var data = handler.DoMethodReturnString("GenerWorkNode");
   if (data.indexOf('err@') == 0) {
        console.log(data);
         _this.$alert("获取表单数据失败,请查看控制台日志,或者联系管理员.", {
           dangerouslyUseHTMLString: true
       });
       return;
   }

   try {

       _this.flowData = JSON.parse(data);
      FrmRBs.push(_this.flowData.Sys_FrmRB);

   } catch (err) {
       console.log(data);
         _this.$alert(" GenerWorkNode转换JSON失败,请查看控制台日志,或者联系管理员.", {
           dangerouslyUseHTMLString: true
       });
      
       return;
   }
   //1.增加表单使用的外部数据源
   var uiBindKeys = _this.flowData["UIBindKey"];
   if (uiBindKeys.length != 0) {
       //获取外部数据源 handler/JavaScript
       var operdata;
       for (var i = 0; i < uiBindKeys.length; i++) {
           var sfTable = new Entity("BP.Sys.SFTable", uiBindKeys[i].No);
           var srcType = sfTable.SrcType;
           if (srcType != null && srcType != "") {
               //Handler 获取外部数据源
               if (srcType == 5) {
                   var selectStatement = sfTable.SelectStatement;
                   if (plant == 'CCFlow')
                       selectStatement = webPath + "/DataUser/SFTableHandler.ashx" + selectStatement;
                   else
                       selectStatement = webPath + "/DataUser/SFTableHandler/" + selectStatement;
                   operdata = DBAccess.RunDBSrc(selectStatement, 1);
               }
               //JavaScript获取外部数据源
               if (srcType == 6) {
                   operdata = DBAccess.RunDBSrc(sfTable.FK_Val, 2);
               }
               _this.flowData[uiBindKeys[i].No] = operdata;
           }
       }

   }

   //2.消息提醒，会签信息，退回信息
   var alertMsgEle="";
   var title="";
   for (  i = 0; i < _this.flowData.AlertMsg.length; i++) {
        var alertMsg = _this.flowData.AlertMsg[i];
        var msg = figure_Template_MsgAlert(alertMsg, i);
        alertMsgEle += msg;
        title = alertMsg.Title;
        if (title.indexOf("请求加签") > 0) {
            //$('#flowInfo').append(alertMsgEle);

        } 

    }

    if (_this.flowData.AlertMsg.length != 0 ) {
        _this.$alert(alertMsgEle, title, {
            confirmButtonText: '确定',
            dangerouslyUseHTMLString: true

        });
    }

   //3.帮助提醒

   //4.发送按钮旁的下拉框

   //5.解析表单
   _this.node = _this.flowData.WF_Node[0];

    if (_this.FormType === 11) {
        //获得配置信息.
        var frmNode = _this.flowData["FrmNode"];
        if (frmNode) {
            frmNode = frmNode[0];
            if (frmNode.FrmSln == 1)
                _this.$route.params.IsReadonly = 1
        }
    }
    //判断类型不同的类型不同的解析表单. 处理中间部分的表单展示.

    if (_this.node.FormType === 5) {
        //GenerTreeFrm(flowData); /*树形表单*/
        return;
    }

    if (_this.node.FormType === 0 || _this.node.FormType === 10) {
        GenerFoolFrm(obj); //傻瓜表单.
    }

    if (_this.node.FormType === 1) {
        GenerFreeFrm(obj);  //自由表单.
    }

    if (_this.node.FormType === 12)
        GenerDevelopFrm(obj);

    //2018.1.1 新增加的类型, 流程独立表单， 为了方便期间都按照自由表单计算了.
    if (_this.node.FormType === 11) {
        if (_this.flowData.FrmNode[0] != null && _this.flowData.FrmNode[0] != undefined)
            if (_this.flowData.FrmNode[0].FrmType == 0)
                GenerFoolFrm(obj); //傻瓜表单.
        if (_this.flowData.FrmNode[0].FrmType == 1)
            GenerFreeFrm(obj);
        if (_this.flowData.FrmNode[0].FrmType == 8)
            GenerDevelopFrm(obj);
    }

    //公文表单
    if (_this.node.FormType == 7) {
        var btnOffice = new Entity("BP.WF.Template.BtnLabExtWebOffice", _this.$route.params.FK_Node);
        if (btnOffice.WebOfficeFrmModel == 1)
            GenerFreeFrm(obj);  //自由表单.
        else
            GenerFoolFrm(obj); //傻瓜表单.
    }

    // 创建script标签，引入外部文件
    //let script = document.createElement('script')
    //script.type = 'text/javascript'
    //script.src = '../datauser/jslibdata/' + _this.flowData.Sys_MapData[0].No + '_Self.js';
    //document.getElementsByTagName('head')[0].appendChild(script)

}

/**
 * 消息提醒内容
 * @param {消息提醒} msgAlert 
 * @param {*} i 
 */
function figure_Template_MsgAlert(msgAlert, i) {
    var _html ='<div>';
    _html +='<span class="titleAlertSpan"> ' + (parseInt(i) + 1) + "&nbsp;&nbsp;&nbsp;" + msgAlert.Title + '</span>';
    _html +='<div>' + msgAlert.Msg + '</div>';
    _html +='</div>';
    return _html;
}
/**
 * 流程保存
 */
function Save(obj){
    var _this = obj;
    //必填项和正则表达式检查
    var formCheckResult = true;

    if (checkBlanks() == false) {
        formCheckResult = false;
    }

    if (checkReg() == false) {
        formCheckResult = false;
    }

    if (formCheckResult == false) {
        return false;
    }

    setToobarDisiable();

    //判断是否启用审核组件
    var iframe = document.getElementById("FWC");
    if (iframe)
        iframe.contentWindow.SaveWorkCheck();

    //树形表单保存   暂时不解析
    /**if (_this.flowData) {
        if (_this.node && _this.node.FormType == 5) {
            if (OnTabChange("btnsave") == true) {
                //判断内容是否保存到待办
                var handler = new HttpHandler("BP.WF.HttpHandler.WF_MyFlow");
                handler.AddPara("FK_Flow", _this.$route.FK_Flow);
                handler.AddPara("FK_Node",  _this.$route.FK_Node);
                handler.AddPara("WorkID",  _this.$route.WorkID);
                handler.AddPara("SaveType", saveType);
                handler.DoMethodReturnString("SaveFlow_ToDraftRole");
            }
            setToobarEnable();
            return;
        }
    }*/

    var params = getFormData(true, true,_this.$route.params);

    var handler = new HttpHandler("BP.WF.HttpHandler.WF_MyFlow");
    $.each(params.split("&"), function (i, o) {
        var param = o.split("=");
        if (param.length == 2 && validate(param[1])) {
            handler.AddPara(param[0], param[1]);
        } else {
            handler.AddPara(param[0], "");
        }
    });
    var data = handler.DoMethodReturnString("Save"); //执行保存方法.

    setToobarEnable();
    //刷新 从表的IFRAME
    var dtls = $('.Fdtl');
    $.each(dtls, function (i, dtl) {
        $(dtl).attr('src', $(dtl).attr('src'));
    });

    if (data.indexOf('保存成功') != 0 || data.indexOf('err@') == 0) {
        _this.$message({
            type: 'error',
            message: data
        });
        console.log(data);
    }
}
/**
 * 流程发送
 */
function Send(obj,isHuiQian){
    var _this = obj;
    
      //必填项和正则表达式检查.
      if (checkBlanks() == false) {
          alert("检查必填项出现错误，边框变红颜色的是否填写完整？");
          return false;
      }
  
      if (checkReg() == false) {
          alert("发送错误:请检查字段边框变红颜色的是否填写完整？");
          return false;
      }
  
      //如果启用了流程流转自定义，必须设置选择的游离态节点
      if ($('[name=TransferCustom]').length > 0) {
          var ens = new Entities("BP.WF.TransferCustoms");
          ens.Retrieve("WorkID", _this.$route.params.WorkID, "IsEnable", 1);
          if (ens.length == 0) {
              alert("该节点启用了流程流转自定义，但是没有设置流程流转的方向，请点击流转自定义按钮进行设置");
              return false;
          }
      }
  
      //树形表单保存
      /*if (_this.flowData) {
          if (_this.node && _this.node.FormType == 5) {
              OnTabChange("btnsave");
              var p = $(document.getElementById("tabs")).find("li");
  
              //查看附件上传的最新数量
              var isSend = true;
              var msg = "";
              $.each(p, function (i, val) {
                  selectSpan = $(val).find("span")[0];
                  var currTab = $("#tabs").tabs("getTab", i);
                  tabText = $(selectSpan).text();
                  var lastChar = tabText.substring(tabText.length - 1, tabText.length);
                  if (lastChar == "*") 
                      tabText = tabText.substring(0, tabText.length - 1);
                  var currScope = currTab.find('iframe')[0];
  
                  var contentWidow = currScope.contentWindow;
                  // 不支持火狐浏览器。
                  var frms = contentWidow.document.getElementsByName("Attach");
                  for (var i = 0; i < frms.length; i++) {
                      msg = frms[i].contentWindow.CheckAthNum();
                      if (msg!="") {
                          msg += "["+tabText+"]表单"+msg+";";
                          isSend = false;
                      }
                  }
              });
              if (isSend == false) {
                  alert(msg);
                  return;
              }
          }
      }*/
  
      var toNodeID = 0;
  
      //含有发送节点 且接收
      if (_this.protoNodes.length > 0) {
          toNodeID = _this.selectNode;
          //获取到达节点的信息
          var toNode ;
          for(var i =0;i<_this.protoNodes.length;i++){
                if(_this.protoNodes[i].No == toNodeID){
                    toNode = _this.protoNodes[i];
                    break;
                }
          }
         
          if (toNode.IsSelectEmps == "1") { //跳到选择接收人窗口
             
              Save(obj,1); //执行保存.
  
              if (isHuiQian == true) {
                _this.dialogFormVisible = true;
                _this.judgeOperation = "HuiQian";
                _this.title="选择会签人";
               // _this.$route.params.push({ToNode: toNodeID});
                  
  
              } else {
                 
                  _this.dialogFormVisible = true;
                  _this.judgeOperation = "sendAccepter";
                  _this.title="选择接收人";
                  console.log('toNodeID--',toNodeID);
                  //_this.$route.params.push({ToNode: toNodeID});
              }
              return false;
  
          } else {
  
              if (isHuiQian == true) {
  
                  Save(obj,1); //执行保存.
                  _this.dialogFormVisible = true;
                  _this.judgeOperation = "HuiQian";
                  _this.title="选择会签人";
                 
                  return false;
              }
          }
      }
  
      //执行发送.
      execSend(obj,toNodeID);
}

function execSend(obj,toNodeID) {
    var _this = obj;
    //先设置按钮等不可用.
    setToobarDisiable();

    //判断是否启用审核组件
    //var iframe = document.getElementById("FWC");
    //if (iframe)
    //    iframe.contentWindow.SaveWorkCheck();

    //保存从表数据
    /*$("[name=Dtl]").each(function (i, obj) {
        var contentWidow = obj.contentWindow;
        if (contentWidow != null && contentWidow.SaveAll != undefined && typeof (contentWidow.SaveAll) == "function") {
            IsSaveTrue = contentWidow.SaveAll();

        }
    });*/


    //组织数据.
    var dataStrs = getFormData(true, true,_this.$route.params) + "&ToNode=" + toNodeID;

    var handler = new HttpHandler("BP.WF.HttpHandler.WF_MyFlow");
    $.each(dataStrs.split("&"), function (i, o) {
        //计算出等号的INDEX
        var indexOfEqual = o.indexOf('=');
        var objectKey = o.substr(0, indexOfEqual);
        var objectValue = o.substr(indexOfEqual + 1);
        if (validate(objectValue)) {
            handler.AddPara(objectKey, objectValue);
        } else {
            handler.AddPara(objectKey, "");
        }
    });
    handler.AddUrlData();
    var data = handler.DoMethodReturnString("Send"); //执行保存方法.

    if (data.indexOf('err@') == 0) { //发送时发生错误

        var reg = new RegExp('err@', "g")
        data = data.replace(reg, '');
        _this.$message({
            type: 'error',
            message: data
        });
       
        setToobarEnable();
        return;
    }
    var url="";
    if (data.indexOf('TurnUrl@') == 0) {  //发送成功时转到指定的URL 
        url = data;
        url = url.replace('TurnUrl@', '');
        window.location.href = url;
        return;
    }

    if (data.indexOf('SelectNodeUrl@') == 0) {
        url = data;
        url = url.replace('SelectNodeUrl@', '');
        window.location.href = url;
        return;
    }



    if (data.indexOf('url@') == 0) {  //发送成功时转到指定的URL 

        if (data.indexOf('Accepter') != 0 && data.indexOf('AccepterGener') == -1) {

            //求出来 url里面的FK_Node=xxxx 
            var params = data.split("&");

            for (var i = 0; i < params.length; i++) {
                if (params[i].indexOf("ToNode") == -1)
                    continue;

                toNodeID = params[i].split("=")[1];
                break;
            }
            _this.dialogFormVisible = true;
            _this.judgeOperation = "sendAccepter";
            _this.$route.params.push({ToNodeID:toNodeID});
           
            return;
        }

        url = data;
        url = url.replace('url@', '');
        window.location.href = url;
        return;
    }
    OptSuc(data,_this);
}

//发送 退回 移交等执行成功后转到  指定页面
function OptSuc(msg,_this) {
    if ($('#returnWorkModal:hidden').length == 0 && $('#returnWorkModal').length > 0) {
        $('#returnWorkModal').modal().hide()
    }
    msg = msg.replace("@查看<img src='/WF/Img/Btn/PrintWorkRpt.gif' >", '')

    msg = msg.replace(/@/g, '<br/>').replace(/null/g, '');
    //var trackA = $('#msgModalContent a:contains("工作轨迹")');
   // var trackImg = $('#msgModalContent img[src*="PrintWorkRpt.gif"]');
    //trackA.remove();
    //trackImg.remove();
    _this.$alert(msg, '发生成功消息', {
        dangerouslyUseHTMLString: true
      });
   
      //跳转页面
      //如果返回url，就直接转向.
      _this.$router.push({
        name: "todolist"
    });
    return;
}


function SysCheckFrm() {
}

/**
 * 保存嵌入式表单
 */
function SaveSelfFrom() {

    // 不支持火狐浏览器。
    var frm = document.getElementById('SelfForm');
    if (frm == null) {
        alert('系统错误,没有找到SelfForm的ID.');
    }
    //执行保存.
    return frm.contentWindow.Save();
}

/**
 * 发送嵌入式表单流程
 */
function SendSelfFrom() {

    if (SaveSelfFrom() == false) {
        alert('表单保存失败，不能发送。');
        return false;
    }
    return true;
}

/**
 * 保存从表数据
 */
function SaveDtlAll(){

}

/**
 * 设置操作按钮不可编辑
 */
function setToobarDisiable() {
    //隐藏下方的功能按钮
    $('.Bar input').css('background', 'gray');
    $('.Bar input').attr('disabled', 'disabled');
}

/**
 * 设置操作按钮可编辑
 */
function setToobarEnable() {
    $('.Bar input').css('background', '');
    $('.Bar input').removeAttr('disabled');
}

function SetFrmReadonly() {


    ('input,textarea,select').attr('disabled', false);
    ('input,textarea,select').attr('readonly', true);
    ('input,textarea,select').attr('disabled', true);

    $('#Btn_Save').attr('disabled', true);
}
/**
 * 获取表单数据
 * @param {是否包含大文本} isCotainTextArea 
 * @param {是否包含路由参数} isCotainRouteParam 
 * @param {组件} route 
 */
function getFormData(isCotainTextArea, isCotainRouteParam,params) {
    var formss = $('form').serialize();

    var formArr = formss.split('&');
    var formArrResult = [];
    var haseExistStr = ",";
    var mcheckboxs = "";
    $.each(formArr, function (i, ele) {
        if (ele.split('=')[0].indexOf('CB_') == 0) {
            //如果ID获取不到值，Name获取到值为复选框多选
            var targetId = ele.split('=')[0];
            if ($('#' + targetId).length == 1) {
                if ($('#' + targetId + ':checked').length == 1) {
                    ele = targetId + '=1';
                } else {
                    ele = targetId + '=0';
                }
                formArrResult.push(ele);
            } else {

                if (mcheckboxs.indexOf(targetId + ",") == -1) {
                    mcheckboxs += targetId + ",";
                    var str = "";
                    $("input[name='" + targetId + "']:checked").each(function (index) {
                        if ($("input[name='" + targetId + "']:checked").length - 1 == index) {
                            str += $(this).val();
                        } else {
                            str += $(this).val() + ",";
                        }
                    });

                    formArrResult.push(targetId + '=' + str);
                }

               
            }

        }
        if (ele.split('=')[0].indexOf('DDL_') == 0) {

            var ctrlID = ele.split('=')[0];

            var item = $("#" + ctrlID).children('option:checked').text();

            var mystr = '';
            mystr = ctrlID.replace("DDL_", "TB_") + 'T=' + item;
            formArrResult.push(mystr);
            formArrResult.push(ele);
            haseExistStr += ctrlID.replace("DDL_", "TB_") + "T" + ",";
        }
        if (ele.split('=')[0].indexOf('RB_') == 0) {
            formArrResult.push(ele);
        }

    });
    $.each(formArr, function (i, ele) {
        var ctrID = ele.split('=')[0];
        if (ctrID.indexOf('TB_') == 0) {
            if (haseExistStr.indexOf(","+ctrID+",") == -1) {
                formArrResult.push(ele);
                haseExistStr += ctrID + ",";
            }
          
               
        }
    });

    //获取表单中禁用的表单元素的值
    var disabledEles = $('#divCCForm :disabled');
    $.each(disabledEles, function (i, disabledEle) {

        var name = $(disabledEle).attr('id');

        switch (disabledEle.tagName.toUpperCase()) {

            case "INPUT":
                switch (disabledEle.type.toUpperCase()) {
                    case "CHECKBOX": //复选框
                        formArrResult.push(name + '=' + encodeURIComponent(($(disabledEle).is(':checked') ? 1 : 0)));
                        break;
                    case "TEXT": //文本框
                    case "HIDDEN":
                        formArrResult.push(name + '=' + encodeURIComponent($(disabledEle).val()));
                        break;
                    case "RADIO": //单选钮
                        name = $(disabledEle).attr('name');
                        var eleResult = name + '=' + $('[name="' + name + '"]:checked').val();
                        if ($.inArray(eleResult, formArrResult) == -1) {
                            formArrResult.push(eleResult);
                        }
                        break;
                }
                break;
            //下拉框            
            case "SELECT":
                formArrResult.push(name + '=' + encodeURIComponent($(disabledEle).children('option:checked').val()));
                var tbID = name.replace("DDL_", "TB_") + 'T';
                if ($("#" + tbID).length == 1) {
                    if (haseExistStr.indexOf("," + tbID + ",") == -1) {
                        formArrResult.push(tbID + '=' + $(disabledEle).children('option:checked').text());
                        haseExistStr += tbID + ",";
                    }
                }
                break;

            //文本区域                    
            case "TEXTAREA":
                formArrResult.push(name + '=' + encodeURIComponent($(disabledEle).val()));
                break;
        }
    });

  

    if (!isCotainTextArea) {
        formArrResult = $.grep(formArrResult, function (value) {
            return value.split('=').length == 2 ? value.split('=')[1].length <= 50 : true;
        });
    }

    formss = formArrResult.join('&');
    var dataArr = [];
    //加上Route中的参数
    if (isCotainRouteParam) {
        var pageDataArr = [];
        for (var data in params) {
            pageDataArr.push(data + '=' + params[data]);
        }
        dataArr.push(pageDataArr.join('&'));
    }
    if (formss != '')
        dataArr.push(formss);
    var formData = dataArr.join('&');

    //为了复选框  合并一下值  复选框的值以  ，号分割
    //用& 符号截取数据
    var formDataArr = formData.split('&');

    var formDataResultObj = {};
    $.each(formDataArr, function (i, formDataObj) {
        //计算出等号的INDEX
        var indexOfEqual = formDataObj.indexOf('=');
        var objectKey = formDataObj.substr(0, indexOfEqual);
        var objectValue = formDataObj.substr(indexOfEqual + 1);
        if (formDataResultObj[objectKey] == undefined) {
            formDataResultObj[objectKey] = objectValue;
        } else {
            formDataResultObj[objectKey] = formDataResultObj[objectKey] + ',' + objectValue;
        }
    });

    var formdataResultStr = '';
    for (var ele in formDataResultObj) {
        formdataResultStr = formdataResultStr + ele + '=' + formDataResultObj[ele] + '&';
    }

    // 处理没有选择的文本框.
    //获得checkBoxNames 格式为: CB_IsXX,CB_IsYY,
    var ids = GenerCheckNames();

    if (ids) {
        var scores = ids.split(",");
        var arrLength = scores.length;
        for (var i = 0; i < arrLength; i++) {
            var field = scores[i];
            var index = formdataResultStr.indexOf(field);
            if (index == -1) {
                if ($("input[name='" + field + "'").length == 1)
                    formdataResultStr += '&' + field + '=0';
                else
                    formdataResultStr += '&' + field + '= ';
            }
        }
    }

    formdataResultStr = formdataResultStr.replace('&&', '&');

    return formdataResultStr;
}

const webUser = new WebUser();
/**
 * 帮助提示
 * @param {启用规则} helpRole 
 * @param {节点ID} FK_Node
 */
function HelpOper(helpRole,FK_Node,_this){
     //判断该节点是否启用了帮助提示 0 禁用 1 启用 2 强制提示 3 选择性提示
     if (helpRole != 0) {
        var count = 0;
        var mypk = webUser.No + "_ND" + FK_Node + "_HelpAlert";
        var userRegedit = new Entity("BP.Sys.UserRegedit");
        userRegedit.SetPKVal(mypk);
        count = userRegedit.RetrieveFromDBSources();
        if (helpRole == 2 || (count == 0 && helpRole == 3)) {
            var filename = webPath + "/DataUser/CCForm/HelpAlert/" + FK_Node + ".htm";
            var htmlobj = $.ajax({ url: filename, async: false });
            if (htmlobj.status == 404)
                return;
            var str = htmlobj.responseText;
            if (str != null && str != "" && str != undefined) {
                _this.$alert(str, '帮助指引', {
                    dangerouslyUseHTMLString: true,
                    beforeClose: (action, instance, done) => {
                        if (count == 0) {
                            //保存数据
                                userRegedit.FK_Emp = webUser.No;
                                userRegedit.FK_MapData = "ND" + FK_Node;
                                userRegedit.Insert();
                            
                        }
                        done();
                    }

                });
            }
        }
    }
}

export{
    initToolBar,
    GenerWorkNode,
    Send,
    Save,
    getFormData,
    SysCheckFrm,
    SaveSelfFrom,
    SendSelfFrom,
    SaveDtlAll,
    HelpOper,
    SetFrmReadonly,
    FrmRBs
};